define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数
            Table.api.init({
                extend: {
                    index_url: 'scanwork/quality_standard/index' + location.search,
                    add_url: 'scanwork/quality_standard/add',
                    edit_url: 'scanwork/quality_standard/edit',
                    del_url: 'scanwork/quality_standard/del',
                    multi_url: 'scanwork/quality_standard/multi',
                    import_url: 'scanwork/quality_standard/import',
                    table: 'quality_standard',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'name', title: __('Name'), operate: 'LIKE'},
                        {field: 'process.name', title: '工序', operate: 'LIKE'},
                        {field: 'product.name', title: '产品', operate: 'LIKE'},
                        {field: 'status', title: __('Status'), searchList: {"1":__('Normal'),"0":__('Hidden')}, formatter: Table.api.formatter.status},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'updatetime', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindevent();
            Controller.api.initCheckItemsForm();
        },
        edit: function () {
            Controller.api.bindevent();
            Controller.api.initCheckItemsForm();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            },
            initCheckItemsForm: function () {
                // 将索引变量设置为Controller的属性，确保在所有方法中都能访问
                Controller.api.categoryIndex = 0;
                Controller.api.itemIndex = 0;
                Controller.api.toleranceIndex = 0;
                
                // 初始化检查项目数据
                var existingData = $('#c-check_items').val();
                if (existingData) {
                    try {
                        var data = JSON.parse(existingData);
                        for (var categoryName in data) {
                            if (data.hasOwnProperty(categoryName)) {
                                Controller.api.addCategory(categoryName, data[categoryName]);
                            }
                        }
                    } catch (e) {
                        console.log('解析检查项目数据失败:', e);
                    }
                }
                
                // 初始化公差要求数据
                var existingToleranceData = $('#c-tolerance_requirements').val();
                if (existingToleranceData) {
                    try {
                        var toleranceData = JSON.parse(existingToleranceData);
                        for (var toleranceName in toleranceData) {
                            if (toleranceData.hasOwnProperty(toleranceName)) {
                                Controller.api.addToleranceItem(toleranceName, toleranceData[toleranceName]);
                            }
                        }
                    } catch (e) {
                        console.log('解析公差要求数据失败:', e);
                    }
                }
                
                // 添加类别按钮事件
                $('#add-category-btn').on('click', function() {
                    Controller.api.addCategory();
                });
                
                // 添加公差要求按钮事件
                $('#add-tolerance-btn').on('click', function() {
                    Controller.api.addToleranceItem();
                });
                
                // 表单提交前更新JSON数据
                $('form').on('submit', function() {
                    Controller.api.updateCheckItemsJson();
                    Controller.api.updateToleranceJson();
                });
            },
            addCategory: function(categoryName, items) {
                categoryName = categoryName || '新检查类别';
                items = items || {};
                
                var categoryId = 'category_' + (++Controller.api.categoryIndex);
                var categoryHtml = '<div class="category-item panel panel-info" data-category-id="' + categoryId + '">' +
                    '<div class="panel-heading">' +
                        '<div class="row">' +
                            '<div class="col-sm-6">' +
                                '<input type="text" class="form-control category-name" value="' + categoryName + '" placeholder="请输入检查类别名称">' +
                            '</div>' +
                            '<div class="col-sm-6 text-right">' +
                                '<button type="button" class="btn btn-success btn-sm add-item-btn">' +
                                    '<i class="fa fa-plus"></i> 添加检查项' +
                                '</button>' +
                                '<button type="button" class="btn btn-danger btn-sm remove-category-btn">' +
                                    '<i class="fa fa-trash"></i> 删除类别' +
                                '</button>' +
                            '</div>' +
                        '</div>' +
                    '</div>' +
                    '<div class="panel-body items-container">' +
                        '<div class="items-list"></div>' +
                    '</div>' +
                '</div>';
                
                $('#categories-container').append(categoryHtml);
                
                // 添加现有项目
                for (var itemName in items) {
                    if (items.hasOwnProperty(itemName)) {
                        Controller.api.addItem(categoryId, itemName, items[itemName]);
                    }
                }
                
                // 绑定事件
                Controller.api.bindCategoryEvents(categoryId);
            },
            addItem: function(categoryId, itemName, itemValue) {
                itemName = itemName || '新检查项';
                itemValue = itemValue || '合格/不合格';
                
                var itemId = 'item_' + (++Controller.api.itemIndex);
                var itemHtml = '<div class="item-row row" data-item-id="' + itemId + '">' +
                    '<div class="col-sm-4">' +
                        '<input type="text" class="form-control item-name" value="' + itemName + '" placeholder="检查项名称">' +
                    '</div>' +
                    '<div class="col-sm-6">' +
                        '<input type="text" class="form-control item-value" value="' + itemValue + '" placeholder="检查标准">' +
                    '</div>' +
                    '<div class="col-sm-2">' +
                        '<button type="button" class="btn btn-danger btn-sm remove-item-btn">' +
                            '<i class="fa fa-trash"></i>' +
                        '</button>' +
                    '</div>' +
                '</div>';
                
                $('div[data-category-id="' + categoryId + '"] .items-list').append(itemHtml);
            },
            bindCategoryEvents: function(categoryId) {
                var $category = $('div[data-category-id="' + categoryId + '"]');
                
                // 添加检查项按钮
                $category.find('.add-item-btn').off('click').on('click', function() {
                    Controller.api.addItem(categoryId);
                });
                
                // 删除类别按钮
                $category.find('.remove-category-btn').off('click').on('click', function() {
                    if (confirm('确定要删除这个检查类别吗？')) {
                        $category.remove();
                    }
                });
                
                // 删除检查项按钮
                $category.find('.remove-item-btn').off('click').on('click', function() {
                    if (confirm('确定要删除这个检查项吗？')) {
                        $(this).closest('.item-row').remove();
                    }
                });
            },
            updateCheckItemsJson: function() {
                var checkItems = {};
                
                $('.category-item').each(function() {
                    var categoryName = $(this).find('.category-name').val().trim();
                    if (categoryName) {
                        checkItems[categoryName] = {};
                        
                        $(this).find('.item-row').each(function() {
                            var itemName = $(this).find('.item-name').val().trim();
                            var itemValue = $(this).find('.item-value').val().trim();
                            
                            if (itemName && itemValue) {
                                checkItems[categoryName][itemName] = itemValue;
                            }
                        });
                    }
                });
                
                $('#c-check_items').val(JSON.stringify(checkItems, null, 2));
            },
            addToleranceItem: function(toleranceName, toleranceValue) {
                toleranceName = toleranceName || '新公差项';
                toleranceValue = toleranceValue || '±0.1mm';
                
                var toleranceId = 'tolerance_' + (++Controller.api.toleranceIndex);
                var toleranceHtml = '<div class="tolerance-row row" data-tolerance-id="' + toleranceId + '">' +
                    '<div class="col-sm-5">' +
                        '<input type="text" class="form-control tolerance-name" value="' + toleranceName + '" placeholder="公差项目名称">' +
                    '</div>' +
                    '<div class="col-sm-5">' +
                        '<input type="text" class="form-control tolerance-value" value="' + toleranceValue + '" placeholder="公差值">' +
                    '</div>' +
                    '<div class="col-sm-2">' +
                        '<button type="button" class="btn btn-danger btn-sm remove-tolerance-btn">' +
                            '<i class="fa fa-trash"></i>' +
                        '</button>' +
                    '</div>' +
                '</div>';
                
                $('#tolerance-items-container').append(toleranceHtml);
                
                // 绑定删除事件
                $('div[data-tolerance-id="' + toleranceId + '"] .remove-tolerance-btn').on('click', function() {
                    if (confirm('确定要删除这个公差要求吗？')) {
                        $(this).closest('.tolerance-row').remove();
                    }
                });
            },
            updateToleranceJson: function() {
                var toleranceItems = {};
                
                $('.tolerance-row').each(function() {
                    var toleranceName = $(this).find('.tolerance-name').val().trim();
                    var toleranceValue = $(this).find('.tolerance-value').val().trim();
                    
                    if (toleranceName && toleranceValue) {
                        toleranceItems[toleranceName] = toleranceValue;
                    }
                });
                
                $('#c-tolerance_requirements').val(JSON.stringify(toleranceItems, null, 2));
            }
        }
    };
    return Controller;
});
